<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="进厂批次" prop="tmpEnterBatchCode">
                    <el-select size="small" class="filter-item" style="width: 150px" v-model="listQuery.tmpEnterBatchCode" placeholder="请选择进厂批次" @change="batchCodeChange">
                        <el-option v-for="item in batchCodeOptions" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属医院" prop="hid">
                    <el-select size="small" clearable class="filter-item" :disabled="true" style="width: 150px" v-model="listQuery.hid" placeholder="所属医院">
                        <el-option v-for="item in hospitalOptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择员工" prop="employeeId">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" v-model="listQuery.employeeId" placeholder="请选择员工">
                        <el-option v-for="item in employeeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="品类" prop="type">
                    <el-select size="small" clearable class="filter-item" placeholder="请选择品类" style="width: 130px" v-model="listQuery.type" @change="typeChange">
                        <el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类" prop="categoryId">
                    <el-select size="small" clearable class="filter-item" placeholder="请选择分类" style="width: 130px" v-model="listQuery.categoryId">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="amount">
                    <el-input size="small" clearable style="width: 150px;" class="filter-item" placeholder="请输入数量" v-model="listQuery.amount">
                    </el-input>
                    <a class="editNum" @click="addItem"><svg-icon icon-class="plus" /></a>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;margin: 20px 0 20px 0;border-top: 1px solid #ddd;padding-top: 15px;">
            录入记录
            <el-button size="small" style="float: right;" class="filter-item" type="primary" icon="el-icon" @click="handleConfirm">提交</el-button>
        </div>
        <el-table :key='tableKey' :data="list" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column align="center" width="60px" type="index" label="序号"></el-table-column>
            <el-table-column align="center" label="计件时间" prop="createTime"></el-table-column>
            <el-table-column align="center" label="员工姓名" prop="employeeName"></el-table-column>
            <el-table-column align="center" label="进厂批次" prop="enterBatchCode"></el-table-column>
            <el-table-column align="center" label="品类" prop="typeName"></el-table-column>
            <el-table-column align="center" label="分类" prop="categoryName"></el-table-column>
            <el-table-column align="center" label="数量" prop="clothesCnt" width="165px;">
                <div slot-scope="scope" class="editNum">
                    <a @click="minNum(scope.row, scope.$index)"><svg-icon icon-class="minus" /></a>
                    <el-input size="small" style="width:90px" placeholder="请输入数量" v-model="scope.row.clothesCnt" />
                    <a @click="addNum(scope.row, scope.$index)"><svg-icon icon-class="plus" /></a>
                </div>
            </el-table-column>
            <el-table-column align="center" label="录入人" prop="createName"></el-table-column>
        </el-table>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { parseTime } from '@/utils'
  import { getWorkers } from '@/api/login'
  import { fetchCategoryList } from '@/api/category'
  import { workloadSaveRecords } from '@/api/workload'
  import { fetchHospitalList, hospitalBatchOrderRecentList, fetchHospitalBatchOrder } from '@/api/hospital'

  export default {
    name: 'PieceOthers',
    props: ['accessMenus'],
    data() {
      return {
        tableKey: 0,
        list: [],
        listQuery: {
          hid: '',
          tmpEnterBatchCode: '',
          enterBatchCode: '',
          employeeId: '',
          categoryId: '',
          amount: 1,
          type: ''
        },
        hospitalOptions: [],
        employeeOptions: [],
        employeeObjs: {},
        batchCodeOptions: [],
        categoryOptions: [],
        categoryObjs: {},
        typeObjs: { '1': '布草', '3': '手术服', '4': '传染服' },
        allTypesOptions: [{ name: '布草', id: 1 }, { name: '手术服', id: 3 }, { name: '传染服', id: 4 }],
        typeOptions: []
      }
    },
    watch: {
      accessMenus(val) {
        if (val) {
          this.genTypes(val)
        }
      }
    },
    created: function() {
      this.genTypes(this.accessMenus)
      this.getEmployee()
      this.getBatchCode()
      this.getHospital()
    },
    computed: {
      ...mapGetters([
        'name',
        'fid'
      ])
    },
    filters: {
      parseTime
    },
    methods: {
      genTypes(menus) {
        this.typeOptions = []
        if (!menus || !menus.length) {
          this.typeOptions = Object.assign([], this.allTypesOptions)
          return
        }
        menus.forEach((item) => {
          const ship = { '1': 0, '3': 1, '4': 2 }
          this.typeOptions.push(this.allTypesOptions[ship[item]])
        })
      },
      getHospital() {
        fetchHospitalList({ page: 1, size: 500, fid: this.fid }).then(response => {
          this.hospitalOptions = response.data && response.data.list || []
        })
      },
      getCategory() {
        fetchCategoryList({ page: 1, size: 500, type: this.listQuery.type }).then(response => {
          this.categoryObjs = {}
          this.categoryOptions = response.data && response.data.list || []
          this.categoryOptions.forEach((item) => {
            this.categoryObjs[item.id] = item.name
          })
        })
      },
      getBatchCode() {
        hospitalBatchOrderRecentList({ page: 1, size: 50 }).then(response => {
          this.batchCodeOptions = response.data || []
        })
      },
      getHospitalByHospitalOrder() {
        if (!this.listQuery.enterBatchCode) return
        fetchHospitalBatchOrder({ code: this.listQuery.enterBatchCode }).then(response => {
          this.listQuery.hid = response.data && response.data.hid || ''
        })
      },
      batchCodeChange() {
        if (this.list.length) {
          this.$confirm('更换进场批次将无法保存当前录入数据', '尚未完成打捆！确定要更换吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.listQuery.enterBatchCode = this.listQuery.tmpEnterBatchCode
            this.getHospitalByHospitalOrder()
            this.list = []
          }).catch(() => {
            this.listQuery.tmpEnterBatchCode = this.listQuery.enterBatchCode
          })
        } else {
          this.listQuery.enterBatchCode = this.listQuery.tmpEnterBatchCode
          this.getHospitalByHospitalOrder()
        }
      },
      getEmployee() {
        getWorkers().then(response => {
          this.employeeObjs = {}
          this.employeeOptions = response.data || []
          this.employeeOptions.forEach((item) => {
            this.employeeObjs[item.id] = item.name
          })
        })
      },
      typeChange() {
        this.getCategory()
        this.listQuery.categoryId = ''
      },
      addNum(row, index) {
        row.clothesCnt++
      },
      minNum(row, index) {
        if (row.clothesCnt <= 1) {
          this.list.splice(index, 1)
          return
        }
        row.clothesCnt--
      },
      addItem() {
        if (!this.listQuery.enterBatchCode) {
          this.$message({ message: '请先选择进厂批次', type: 'error', showClose: true })
          return
        }
        if (!this.listQuery.employeeId) {
          this.$message({ message: '请先选择员工', type: 'error', showClose: true })
          return
        }
        if (!this.listQuery.type) {
          this.$message({ message: '请先选择品类', type: 'error', showClose: true })
          return
        }
        if (!this.listQuery.categoryId) {
          this.$message({ message: '请先选择分类', type: 'error', showClose: true })
          return
        }
        if (!this.listQuery.amount || !/^\d+$/.test(this.listQuery.amount)) {
          this.$message({ message: '请输入数量', type: 'error', showClose: true })
          return
        }
        let has = false
        let inIndex = -1
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].uid === this.listQuery.employeeId && this.list[i].type === this.listQuery.type && this.list[i].categoryId === this.listQuery.categoryId) {
            has = true
            inIndex = i
            break
          }
        }
        if (has && inIndex > -1) {
          this.list[inIndex].clothesCnt = parseInt(this.list[inIndex].clothesCnt) + parseInt(this.listQuery.amount)
        } else {
          const item = {
            uid: this.listQuery.employeeId,
            categoryId: this.listQuery.categoryId,
            clothesCnt: this.listQuery.amount,
            employeeName: this.employeeObjs[this.listQuery.employeeId],
            enterBatchCode: this.listQuery.enterBatchCode,
            type: this.listQuery.type,
            typeName: this.typeObjs[this.listQuery.type],
            categoryName: this.categoryObjs[this.listQuery.categoryId],
            createName: this.name,
            createTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
          }
          this.list.push(item)
        }
      },
      handleConfirm(row) {
        if (!this.listQuery.enterBatchCode) {
          this.$message({ message: '请先选择进厂批次', type: 'error', showClose: true })
          return
        }
        if (!this.listQuery.type) {
          this.$message({ message: '请先选择品类', type: 'error', showClose: true })
          return
        }
        if (!this.list || !this.list.length) {
          this.$message({ message: '请先录入数据', type: 'error', showClose: true })
          return
        }
        const recordList = []
        this.list.forEach((item) => {
          recordList.push({ uid: item.uid, categoryId: item.categoryId, clothesCnt: item.clothesCnt })
        })
        workloadSaveRecords(this.listQuery.enterBatchCode, this.listQuery.type, recordList).then(response => {
          if (response.data) {
            this.$message({ message: '计件成功', type: 'success', showClose: true })
            this.list = []
          }
        })
      }
    }
  }
</script>

<style scoped>
    .editNum div, .editNum a{
        float: left;
        text-align: center;
    }
    a.editNum, .editNum a {
        font-size: 25px;
        line-height: 32px;
    }
</style>
